package kr.ac.konkuk.db.quadtree.node;

import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Queue;

import kr.ac.konkuk.db.quadtree.RowKey;
import kr.ac.konkuk.db.quadtree.callback.GeometryProvider;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;

public class Root extends Node {
	public Root(Envelope env, GeometryProvider provider) {
		super("0", env, provider);
	}
	
	public void visits(NodeVisitor visitor) {
		visits(this, visitor);
	}
	
	private boolean visits(NodeBase bnode, NodeVisitor visitor) {
		if (!visitor.visit(bnode))
			return false;
		
		if (bnode instanceof Node) {
			Node node = (Node)bnode;
			for (NodeBase subnode : node.subnodes) {
				if (!visits(subnode, visitor))
					return false;
			}
		}
		
		return true;
	}

	public boolean remove(RowKey rowKey) {
		Geometry geom = super.geometryProvider.getGeometry(rowKey);
		Queue<Coordinate> coords = new LinkedList<Coordinate>();
		coords.addAll(Arrays.asList(geom.getCoordinates()));
		boolean removed = false;
		while (!coords.isEmpty()) {
			Coordinate coord = coords.remove();
			for (Coordinate removedCoord : super.remove(rowKey, coord)) {
				coords.remove(removedCoord);
				removed = true;
			}
		}
		
		return removed;
	}
	
	
}
